package com.itec.learn.java.abc.wait;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 有三个线程分别打印A、B、C,请用多线程编程实现，在屏幕上循环打印10次ABCABC…
 * @author chenyiqun
 */
public class WaitExample {

    public static void main(String[] args) {
        WaitExample example = new WaitExample();
        Letters l = new Letters();
        ExecutorService servive = Executors.newFixedThreadPool(3);
        servive.execute(example.new ThreadPrint(l,'A'));
        servive.execute(example.new ThreadPrint(l,'B'));
        servive.execute(example.new ThreadPrint(l,'C'));
        servive.shutdown();

    }

    private class ThreadPrint implements Runnable{
        private Letters letters;
        private char name;

        public ThreadPrint (Letters letters, char name){
            this.letters = letters;
            this.name = name;
        }
        @Override
        public void run() {
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (letters){
                        while (letters.get()!=name){
                            letters.wait();
                        }
                        letters.print();
                        letters.next();
                        letters.notifyAll();
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }

}


